<template>
  <div class="home">
    <mt-header fixed title="商品列表"></mt-header>
    <mt-tab-container v-model="active" >
        <mt-tab-container-item id="首页">
            <mt-cell class="item" v-for="item in goods" :key="item.aid">
              <img :src="item.img" alt="">
              <h4>{{item.title}}</h4>
              <p class="cp">{{item.desc}}</p>
              <p class="price">￥{{item.price}}元</p>
              <mt-button type="danger" size="small" class="btn" @click.native="buy(item)">购买</mt-button>
            </mt-cell>
        </mt-tab-container-item>
      </mt-tab-container>
      <mt-button @click="moreClick()" class="mbtn" type="danger" size="large">查看更多</mt-button>
  </div>
</template>

<script>
import { getGoodsData } from '../services/goods';
import { shopCart } from '../services/product_type';
import cookie from 'js-cookie';
import { Toast } from 'mint-ui'

export default {
  name: 'Home',
  data () {
    return {
      active:'首页',
      goods:[],
      start: 0,
      end: 5,
    }
  },
  methods:{
    buy(item){
      console.log(item);
      if (cookie.get('userName')) {
        shopCart({
        userName: cookie.get('userName'),
        goodName: item.title,
        goodImg: item.img,
        goodPrice: item.price,
        goodBuyCount: 1,
        }).then( res => {
        console.log(res);
        this.$eventBus.$emit('addToShopCart', 1);
        }).catch( err => {
        console.log(err);
        }) 
      } else {
        Toast({
          message: '请先登陆……',
          position: 'middle',
          duration: 5000,
        });
      }
    },
    moreClick() {
      this.start += 5;
      this.end += 5;
      let good = getGoodsData(this.start, this.end);
      this.goods = this.goods.concat(good);
    }
  },
  created(){
    this.goods = getGoodsData(this.start, this.end);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.item{
  height:140px;
  position: relative;
}
.item img{
  width:100px;
  height: 100px;
  background-color: gray;
  position: absolute;
  left:20px;
  top:20px;
  border-radius: 0;
}
.item h4{
  position: absolute;
  color:black;
  left:140px;
}
.item .cp{
  position: absolute;
  left:140px;
  top:50px;
  font-size: 0.8rem;
}
.item .price{
  position: absolute;
  left: 140px;
  top: 25px;
  color:black;
  margin-right: 10px;
}
.home .mbtn{
  font-size: 0.8rem;
}
.item .btn{
  position: absolute;
  right:30px;
  bottom:10px;
}
.btnMore{
  position: absolute;
  right:30px;
}
</style>

